package com.pet_service.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pet_service.entity.HomeServiceType;
import com.pet_service.entity.OrderHomeService;
import com.pet_service.enums.TOrderHomeServiceStatus;
import com.pet_service.result.Result;
import com.pet_service.service.HomeServiceTypeService;
import com.pet_service.service.OrderHomeServiceService;
import com.pet_service.vo.PageBean;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 邹全伸
 * @version 1.0
 * @date 2025-09-25 09:08
 */
//上门服务控制器
@Slf4j
@Tag(name = "上门服务接口")
@RestController//作用是将Controller组件注册为Bean
@RequestMapping("/home")//作用是定义请求的URL
public class HomeServiceController {
    @Resource
    private HomeServiceTypeService homeServiceTypeService;

    @Resource
    private OrderHomeServiceService orderHomeServiceService;

    //分页查询上门服务类型
    @PostMapping("/list")
    //权限控制  homeService:type:view是数据库中权限的标识
    @PreAuthorize("hasAuthority('service:home:type:view')")
    public Result ServiceTypeList(@RequestBody PageBean pageBean) {
        log.info("分页查询上门服务类型,参数:{}",pageBean);
        //mybatis-plus提供的page方法
        Page<HomeServiceType> page=new Page<>(pageBean.getPageNum(),pageBean.getPageSize());
        //创建查询条件,QueryWrapper是mybatis-plus提供的条件构造器
        QueryWrapper<HomeServiceType> queryWrapper=new QueryWrapper<>();
//        //模糊查询
//        queryWrapper.like(pageBean.getQuery()!=null,"service_name",pageBean.getQuery().trim());
        //模糊查询
        if (pageBean.getQuery() != null && !pageBean.getQuery().trim().isEmpty()) {
            queryWrapper.like("service_name", pageBean.getQuery().trim());
        }
        //分页查询
        IPage<HomeServiceType> iPage=homeServiceTypeService.page(page,queryWrapper);
        return Result.ok(iPage);
    }

    //添加查询上门服务类型
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('Service:home:type:add')")
    public Result addServiceType(@RequestBody HomeServiceType homeServiceType) {
        log.info("添加上门服务类型,参数:{}",homeServiceType);
        //检查是否存在相同的服务类型
        if (homeServiceTypeService.count(new QueryWrapper<HomeServiceType>().eq("service_name",homeServiceType.getService_name()))>0){
            return Result.fail("服务类型已存在");
        }
        return homeServiceTypeService.save(homeServiceType)?Result.ok():Result.fail();
    }

    //修改查询上门服务类型
    @PostMapping("/edit")
    @PreAuthorize("hasAuthority('Service:home:type:edit')")
    public Result editServiceType(@RequestBody HomeServiceType homeServiceType) {
        log.info("修改上门服务类型,参数:{}",homeServiceType);
        //修改时,检查是否存在相同的服务类型
        if (homeServiceTypeService.count(new QueryWrapper<HomeServiceType>().eq("service_name",homeServiceType.getService_name()).ne("id",homeServiceType.getId()))>0){
            return Result.fail("服务类型已存在");
        }
        return homeServiceTypeService.updateById(homeServiceType)?Result.ok():Result.fail();
    }

    //删除上门服务类型
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('Service:home:type:delete')")
    public Result deleteServiceType(@PathVariable Integer id) {
        log.info("物理删除上门服务类型,参数:{}", id);
        if (id == null || id <= 0) {
            return Result.fail("参数错误");
        }
        // 调用自定义的物理删除方法
        boolean success = homeServiceTypeService.physicalDelete(id);
        return success ? Result.ok() : Result.fail("删除失败（记录不存在）");
    }


    //------------------------------------------------上门服务订单管理-------------------------------------------------------------------
    //OrderHomeService:order_id,service_type_id,service_time,service_address_id,service_status,service_staff_id

    //根据订单id和服务类型id查询上门服务的订单
    @GetMapping("/order/{order_id}/{service_type_id}")
    @PreAuthorize("hasAuthority('Service:home:order:view')")
    public Result setOrderIdAndServiceId(@PathVariable Integer order_id, @PathVariable Integer service_type_id) {
        log.info("根据订单id和服务类型id查询上门服务的订单,参数:{},{}", order_id, service_type_id);
        return Result.ok(homeServiceTypeService.setOrderIdAndServiceId(order_id, service_type_id));
    }

    // 分页查询上门服务订单
    @PostMapping("/order/list")
    @PreAuthorize("hasAuthority('Service:home:order:view')")
    public Result orderList(@RequestBody PageBean pageBean) {
        log.info("分页查询上门服务订单,参数:{}", pageBean);
        // 创建分页对象
        Page<OrderHomeService> page = new Page<>(pageBean.getPageNum(), pageBean.getPageSize());
        // 创建查询条件
        QueryWrapper<OrderHomeService> queryWrapper = new QueryWrapper<>();
        // 执行分页查询（带地址信息）
        IPage<OrderHomeService> iPage = orderHomeServiceService.pageWithAddressInfo(page, queryWrapper);
        return Result.ok(iPage);
    }

    //添加上门服务订单
    @PostMapping("/order/add")
    @PreAuthorize("hasAuthority('Service:home:order:add')")
    public Result addOrder(@RequestBody OrderHomeService orderHomeService) {
        log.info("添加上门服务订单,参数:{}", orderHomeService);
        return orderHomeServiceService.save(orderHomeService)?Result.ok():Result.fail();
    }

    //修改上门服务订单
    @PostMapping("/order/edit")
    @PreAuthorize("hasAuthority('Service:home:order:edit')")
    public Result editOrder(@RequestBody OrderHomeService orderHomeService) {
        log.info("修改上门服务订单,参数:{}", orderHomeService);
        return orderHomeServiceService.updateById(orderHomeService)?Result.ok():Result.fail();
    }

    // 删除上门服务订单
    @DeleteMapping("/order/delete/{id}")
    @PreAuthorize("hasAuthority('Service:home:order:delete')")
    public Result deleteOrder(@PathVariable Integer id) {
        log.info("删除上门服务订单,参数:{}", id);

        if (id == null || id <= 0) {
            return Result.fail("参数错误");
        }

        // 获取订单信息
        OrderHomeService orderHomeService = orderHomeServiceService.getById(id);
        if (orderHomeService == null) {
            return Result.fail("订单不存在");
        }

        // 检查订单状态，只有已完成的订单才能删除
        TOrderHomeServiceStatus status = orderHomeService.getService_status();
        if (status != TOrderHomeServiceStatus.COMPLETED) {
            return Result.fail("只有已完成的订单才能删除");
        }

        // 执行物理删除操作
        boolean success = orderHomeServiceService.physicalDelete(id);
        return success ? Result.ok() : Result.fail("删除失败");
    }



    //查询服务订单的状态,PENDING(0, "待执行"),EXECUTING(1, "执行中"),COMPLETED(2, "已完成");
    @GetMapping("/order/status/{id}")
    @PreAuthorize("hasAuthority('Service:home:order:view')")
    public Result getOrderStatus(@PathVariable Integer id) {
        log.info("查询服务订单的状态,参数:{}", id);
        return Result.ok(orderHomeServiceService.getOrderStatus(id));
    }
}

